using Cysharp.Threading.Tasks;
using GameFramework;
using GameFramework.Resource;
using UnityEngine;
using UnityGameFramework.Runtime;

namespace DTFramework
{
    /// <summary>
    /// 动态资源的加载与卸载
    /// </summary>
    public static class ResourceExtension
    {
        /// <summary>
        /// 异步加载资产 并创建对象
        /// </summary>
        /// <typeparam name="T">加载类型</typeparam>
        /// <param name="resource">组件</param>
        /// <param name="assetPath">加载路径</param>
        /// <returns></returns>
        public static async UniTask<T> InstantiateAsync<T>(this ResourceComponent resource, string assetPath, bool isPersistent = false) where T : Component
        {
            var asset = await resource.LoadAssetAsync(assetPath);
            var target = GameObject.Instantiate(asset);
            if (isPersistent) GameObject.DontDestroyOnLoad(target);
            return target.GetComponent<T>();
        }

        /// <summary>
        /// 异步加载资产
        /// </summary>
        /// <typeparam name="T">加载类型</typeparam>
        /// <param name="resource">组件</param>
        /// <param name="assetPath">加载路径</param>
        /// <returns></returns>
        public static UniTask<GameObject> LoadAssetAsync(this ResourceComponent resource, string assetPath)
        {
            var uniTcs = new UniTaskCompletionSource<GameObject>();
            resource.LoadAsset(assetPath, typeof(GameObject), AssetPriority.UIFormAsset, new LoadAssetCallbacks(
           (assetName, asset, duration, userData) =>
           {
               var tObject = asset as GameObject;
               uniTcs.TrySetResult(tObject);
           },
           (assetName, status, errorMessage, userData) =>
           {
               Log.Error($"初始化加载 ScriptableObject 失败：{assetName}，status：{status}，errorMessage：{errorMessage}");
               uniTcs.TrySetException(new GameFrameworkException(errorMessage));
           }));
            return uniTcs.Task;
        }

    }
}